package com.example.shangguigu.base64;

import org.bouncycastle.util.encoders.Hex;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @DESCRIPTION:
 * @USER: shg
 * @DATE: 2023/2/24 22:01
 */
public class Base64Demo {

    public static void main(String[] args) throws UnsupportedEncodingException {
        Base64Test1();
        System.out.println("******");
        Base64Test2();
        System.out.println("******");


        System.out.println(URLEncoder.encode("严", "UTF-8"));    // %E4%B8%A5
    }

    private static void Base64Test2() {

        String str = "Man";

        // 字符串的原始字节数组
        byte[] b1 = str.getBytes();
        printBytes(b1, "原始字符串的字节");

        // 得到Base64编码后的字节数组
        byte[] encode = Base64.getEncoder().encode(str.getBytes());
        printBytes(encode, "Base64编码后的字节");
        // 得到Base64编码后的字符串
        String string = Base64.getEncoder().encodeToString(str.getBytes());
        System.out.println(string);

        // 得到Base64解码后的原始字符串的字节数组
        byte[] decode = Base64.getDecoder().decode(encode);
        printBytes(decode, "Base64解码后的字符数组");
        byte[] decode1 = Base64.getDecoder().decode(string);
        printBytes(decode1, "Base64解码后的字符数组_");
    }

    private static void printBytes(byte[] bytes, String desc) {
        System.out.println("---" + desc + "---");
        for (byte aByte : bytes) {
            System.out.println(aByte + "\t");
        }
    }

    private static void Base64Test1() {
        String str = "Man";

        System.out.println("---原始信息---");
        byte[] bytes = str.getBytes();
        for (byte aByte : bytes) {
            System.out.print((char) aByte + "   ");
            System.out.print(aByte + "   ");
            System.out.println(Integer.toBinaryString(aByte));
        }
        System.out.println("---使用Base64编码后的信息---");

        // 使用Base64编码，得到编码后的字节（这个就是在网络中传输的字节流）
        byte[] encode = Base64.getEncoder().encode(str.getBytes());
        for (byte b : encode) {
            System.out.print((char) b + "   ");
            System.out.print(b + "   ");
            System.out.println(Integer.toBinaryString(b));
        }
        System.out.println("---使用Base64解码后的信息---");

        // 使用Base64解码，得到解码后的字节
        byte[] decode = Base64.getDecoder().decode(encode);
        for (byte b : decode) {
            System.out.print((char) b + "   ");
            System.out.print(b + "   ");
            System.out.println(Integer.toBinaryString(b));
        }
    }

}
